package com.glkj.vipsystem.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.entity.ao.GoodsAO;
import com.glkj.vipsystem.entity.ao.ShopAO;
import com.glkj.vipsystem.entity.gen.GoodsPrice;
import com.glkj.vipsystem.entity.gen.Stock;
import com.glkj.vipsystem.mapper.GoodsMapper;
import com.glkj.vipsystem.service.IGoodsPriceService;
import com.glkj.vipsystem.service.IGoodsService;
import com.glkj.vipsystem.service.IShopService;
import com.glkj.vipsystem.service.IStockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * Goods 服务实现类
 * </p>
 *
 * @author Limuchan
 * @since 2019-09-06 10:18:36
 */
@Service
public class GoodsService extends ServiceImpl<GoodsMapper, GoodsAO> implements IGoodsService {

    @Resource
    private IStockService stockService;
    @Resource
    private IShopService shopService;
    @Resource
    private IGoodsPriceService goodsPriceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(GoodsAO goods) {
        if (goods == null) {
            throw new BizException("商品信息错误");
        }
        this.insert(goods);

        Integer companyId = goods.getCompanyId();
        List<ShopAO> shopAOS = shopService.selectList(new EntityWrapper<ShopAO>().eq("company_id", companyId));
        if (CollectionUtils.isEmpty(shopAOS)) {
            return;
        }
        List<Integer> shopIds = shopAOS.stream().map(ShopAO::getId).collect(Collectors.toList());
        for (Integer shopId : shopIds) {
            stockService.addStock(shopId, goods.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Integer> goodsIds) {
        if (CollectionUtils.isEmpty(goodsIds)) {
            return;
        }
        this.deleteBatchIds(goodsIds);
        // 删除库存
        stockService.delete(
                new EntityWrapper<Stock>()
                        .in("goods_id", goodsIds)
        );
        // 同时删除商品店铺价格
        goodsPriceService.delete(
                new EntityWrapper<GoodsPrice>()
                        .in("goods_id", goodsIds)
        );
    }
}